package wc

import (
	"github.com/astaxie/beego/context"
	"github.com/silenceper/wechat"
	"github.com/silenceper/wechat/cache"
	"github.com/silenceper/wechat/miniprogram"
	"gopkg.in/mgo.v2/bson"
	"main/database"
	"main/env"
)

var MiniP *miniprogram.MiniProgram

func init() {
	rcache := cache.NewRedis(&cache.RedisOpts{
		Host:        env.RedisHost,
		Database:    env.RedisDB,
		MaxIdle:     10,
		MaxActive:   300,
		IdleTimeout: 25,
	})
	config := &wechat.Config{
		AppID:     env.AppID,
		AppSecret: env.AppSecret,
		Cache:     rcache,
	}
	wc := wechat.NewWechat(config)

	MiniP = wc.GetMiniProgram()
}

// 登录
func Login(ctx *context.Context) {
	object := make(map[string]interface{})
	code := ctx.Input.Query("code")
	if code == "" {
		Response(ctx, 0, "code is required", object)
		return
	}

	// 获取Code2Session
	res, err := MiniP.Code2Session(code)
	if err != nil {
		Response(ctx, 0, "code2session error", res)
		return
	}
	if res.ErrCode != 0 {
		Response(ctx, 0, res.ErrMsg, res)
		return
	}

	var r ResCode2Session
	r.CopyFromCode2Session(&res)

	ds := database.NewSessionStore()
	defer ds.Close()
	con := ds.C("users")

	var origin ResCode2Session
	// 查找
	if err := con.Find(bson.M{"union_id": r.UnionID}).One(&origin); err != nil {
		if err.Error() == database.GetErrNotFound().Error() {
			// 插入
			con.Insert(&r)
			Response(ctx, 1, "code2session success", res)
			return
		} else {
			Response(ctx, 0, err.Error(), res)
			return
		}
	}

	// 原来就有
	_ = con.Update(bson.M{"union_id": r.UnionID}, r)
	Response(ctx, 1, "code2session success", res)
	return
}
